package com.yn.service.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yn.common.exception.TransitException;
import com.yn.common.model.article.ArticleContent;
import com.yn.common.model.article.ArticleTitleManage;
import com.yn.common.model.system.SystemConfig;
import com.yn.common.model.user.User;
import com.yn.common.page.BasePage;
import com.yn.common.request.sc.ArticleManageRequest;
import com.yn.common.request.sc.ArticleManageSearchRequest;
import com.yn.common.request.sc.ArticleTransitSearchRequest;
import com.yn.common.request.sc.PageParamRequest;
import com.yn.common.response.zy.DictResponse;
import com.yn.common.vo.ArticleManageVO;
import com.yn.common.vo.ArticleVo;
import com.yn.service.dao.ArticleContentDao;
import com.yn.service.dao.ArticleTitleManageDao;
import com.yn.service.service.IArticleTitleManageService;
import com.yn.service.service.SystemConfigService;
import com.yn.service.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 栏目管理 服务实现类
 * </p>
 *
 * @author xuquanjun
 * @since 2025-06-26
 */
@Service
@Slf4j
public class ArticleTitleManageServiceImpl extends ServiceImpl<ArticleTitleManageDao, ArticleTitleManage> implements IArticleTitleManageService {

    @Autowired
    private UserService userService;
    @Autowired
    private ArticleTitleManageDao dao;
    @Autowired
    private ArticleContentDao articleContentDao;

    @Autowired
    private SystemConfigService systemConfigService;

    @Override
    @Transactional
    public boolean create(ArticleManageRequest request) {
        log.info("新增栏目信息,{}",request);
        //获取用户信息
        //Integer userId = userService.getUserIdException();
        //根据栏目类型查询数据库
        ArticleTitleManage one = lambdaQuery().eq(ArticleTitleManage::getTitleType, request.getTitleType()).one();
        if(one != null){
            throw new TransitException("栏目已存在");
        }
        ArticleTitleManage manage = new ArticleTitleManage();
        BeanUtil.copyProperties(request,manage);
        //manage.setCreateId(userId);
        //manage.setUpdateId(userId);
        return save(manage);
    }


    @Override
    @Transactional
    public boolean updateTitleInfo(ArticleManageRequest request) {
        log.info("修改栏目修改内容：{}",  request);
        if (request.getId() == null) {
            return false;
        }
        ArticleTitleManage one = lambdaQuery().eq(ArticleTitleManage::getTitleType, request.getTitleType())
                .eq(ArticleTitleManage::getTitleName, request.getTitleName()).one();
        if(one != null && !Objects.equals(one.getId(), request.getId())){
            throw new TransitException("栏目已存在");
        }
        ArticleTitleManage manage = new ArticleTitleManage();
        BeanUtil.copyProperties(request,manage);
        //获取用户id
        //Integer userId = userService.getUserIdException();
       // manage.setUpdateId(userId);
        return updateById(manage);
    }

    @Override
    @Transactional
    public boolean deleteById(Long id) {
        log.info("删除文章内容管理,{}", id);
        ArticleTitleManage manage = baseMapper.selectById(id);
        if(manage == null){
            throw new TransitException("文章已被删除");
        }
        boolean remove = lambdaUpdate().eq(ArticleTitleManage::getId, id).remove();
        if(!remove){
            throw new TransitException("删除失败");
        }
        LambdaUpdateWrapper<ArticleContent> wrapper = Wrappers.lambdaUpdate();
        wrapper.eq(ArticleContent::getTitleManageId, id);
        int delete = articleContentDao.delete(wrapper);
        return delete > 0;
    }

    @Override
    public PageInfo<ArticleManageVO> getAdminList(ArticleManageSearchRequest request, PageParamRequest pageParamRequest) {
        Page<ArticleTitleManage> articlePage = PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());
        LambdaQueryWrapper<ArticleTitleManage> lambdaQuery = Wrappers.lambdaQuery();
        if(request.getTitleType()!= null && !request.getTitleType().isEmpty()){
            lambdaQuery.eq(ArticleTitleManage::getTitleType, request.getTitleType());
        }
        if(request.getKeywords()!= null && !request.getKeywords().isEmpty()){
            lambdaQuery.and(i -> i.or().like(ArticleTitleManage::getTitleName, request.getKeywords())
                    .or().like(ArticleTitleManage::getTitleIntro, request.getKeywords()));
        }
        List<ArticleTitleManage> articleTitleManageList = dao.selectList(lambdaQuery);
        ArrayList<ArticleManageVO> articleVoArrayList = new ArrayList<>();
        if(articleTitleManageList == null || articleTitleManageList.isEmpty()){
            return BasePage.copyPageInfo(articlePage, articleVoArrayList);
        }
        for (ArticleTitleManage articleTitleManage : articleTitleManageList) {
            ArticleManageVO articleVo = new ArticleManageVO();
            BeanUtil.copyProperties(articleTitleManage, articleVo);
            //String creator = userService.getInfoByUid(articleTitleManage.getCreateId()).getNickname();
            //String updater = userService.getInfoByUid(articleTitleManage.getUpdateId()).getNickname();
            //articleVo.setCreateBy(creator);
            //articleVo.setUpdateBy(updater);
            articleVoArrayList.add(articleVo);
        }
        return BasePage.copyPageInfo(articlePage, articleVoArrayList);
    }

    /**
     * 获取字典数据
     * @param dictName 字典名称
     * @return 字典数据集合
     */
    @Override
    public List<DictResponse> showDictType(String dictName) {
        List<SystemConfig> infoByName = systemConfigService.getInfoByName(dictName);
        if(CollUtil.isEmpty(infoByName)){
            return new ArrayList<>();
        }
        ArrayList<DictResponse> response = new ArrayList<>(infoByName.size());
        for (SystemConfig config : infoByName) {
            response.add(DictResponse.transform(config));
        }
        return response;
    }

    /**
     * 根据字段名称获取字典项信息
     * @param dictName 字段名称
     * @return Map<value,name>
     */
    public Map<String, String> showDictType2Map(String dictName){
        Map<String, String> mapByName = systemConfigService.getMapByName(dictName);
        if(CollUtil.isEmpty(mapByName)){
            return new HashMap<>();
        }
        return mapByName;
    }
}
